import os
import pandas as pd


def mkdir(file_path):
    directory = os.path.dirname(file_path)
    try:
        if not os.path.exists(directory):
            os.makedirs(directory)
        print("File written successfully.")
    except PermissionError:
        print("Permission denied to create directory or write file.")
    except FileExistsError:
        print("Directory already exists.")


def to_xlsx(data, path):
    mkdir(path)
    # 创建一个ExcelWriter对象，指定使用xlsxwriter作为引擎
    writer = pd.ExcelWriter(path, engine='xlsxwriter')

    # 将DataFrame写入Excel文件的工作表中（这里默认写入Sheet1）
    data.to_excel(writer, sheet_name='Sheet1', index=False)

    # 获取工作簿对象
    workbook = writer.book

    # 创建格式对象，设置字体为微软雅黑，字号为9
    format_font = workbook.add_format()
    format_font.set_font_name('微软雅黑')
    format_font.set_font_size(9)

    # 对整个工作表应用字体格式（这里可以根据实际需求灵活调整应用范围，比如特定列、行等）
    worksheet = writer.sheets['Sheet1']
    worksheet.set_column(0, data.shape[1] - 1, None, format_font)

    # 保存文件
    writer._save()
